#!/bin/bash

# WordPress环境安装脚本 - 简化版，绕过MySQL问题

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查root权限
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本必须以root权限运行"
        exit 1
    fi
}

# 彻底重置MySQL
reset_mysql() {
    log_info "彻底重置MySQL..."
    
    # 停止MySQL
    systemctl stop mysql 2>/dev/null || true
    
    # 完全卸载MySQL
    apt remove --purge mysql-server mysql-client mysql-common mysql-server-core-* mysql-client-core-* -y
    apt autoremove -y
    
    # 清理所有配置文件和数据
    rm -rf /etc/mysql /var/lib/mysql /var/log/mysql
    rm -rf /root/.mysql_history
    
    # 清理残留配置
    apt autoclean -y
    
    log_success "MySQL已彻底清除"
}

# 重新安装MySQL
install_mysql_fresh() {
    log_info "重新安装MySQL..."
    
    # 更新包列表
    apt update
    
    # 安装MySQL（不配置）
    DEBIAN_FRONTEND=noninteractive apt install -y mysql-server
    
    # 确保目录存在
    mkdir -p /var/run/mysqld
    chown mysql:mysql /var/run/mysqld
    
    # 启动MySQL
    systemctl enable mysql
    systemctl start mysql
    
    # 等待启动
    sleep 5
    
    # 检查状态
    if systemctl is-active --quiet mysql; then
        log_success "MySQL安装成功"
    else
        log_error "MySQL启动失败"
        exit 1
    fi
}

# 手动配置MySQL
configure_mysql_manual() {
    log_info "手动配置MySQL..."
    
    # 生成密码
    MYSQL_ROOT_PASSWORD="RootPassword123!"
    MYSQL_WP_PASSWORD="WpPassword123!"
    
    # 保存密码
    echo "MySQL Root Password: $MYSQL_ROOT_PASSWORD" > /root/mysql_passwords.txt
    echo "MySQL WordPress Password: $MYSQL_WP_PASSWORD" >> /root/mysql_passwords.txt
    chmod 600 /root/mysql_passwords.txt
    
    # 使用mysql_secure_installation的替代方案
    mysql -u root <<EOF
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$MYSQL_ROOT_PASSWORD';
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;
EOF
    
    # 创建WordPress数据库
    mysql -u root -p"$MYSQL_ROOT_PASSWORD" <<EOF
CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'wordpress_user'@'localhost' IDENTIFIED BY '$MYSQL_WP_PASSWORD';
GRANT ALL PRIVILEGES ON wordpress.* TO 'wordpress_user'@'localhost';
FLUSH PRIVILEGES;
EOF
    
    log_success "MySQL配置完成"
}

# 安装Nginx
install_nginx() {
    log_info "安装Nginx..."
    apt install -y nginx
    systemctl enable nginx
    systemctl start nginx
    log_success "Nginx安装完成"
}

# 安装PHP
install_php() {
    log_info "安装PHP 8.4..."
    
    apt install -y software-properties-common
    add-apt-repository -y ppa:ondrej/php
    apt update
    
    apt install -y php8.4 php8.4-fpm php8.4-mysql php8.4-curl php8.4-gd \
    php8.4-mbstring php8.4-xml php8.4-zip php8.4-opcache php8.4-redis
    
    systemctl enable php8.4-fpm
    systemctl start php8.4-fpm
    log_success "PHP安装完成"
}

# 安装Redis
install_redis() {
    log_info "安装Redis..."
    apt install -y redis-server
    systemctl enable redis-server
    systemctl start redis-server
    log_success "Redis安装完成"
}

# 配置网站
setup_website() {
    log_info "配置网站..."
    
    # 创建网站目录
    mkdir -p /var/www/html/wordpress
    cd /var/www/html/wordpress
    
    # 下载WordPress
    wget -O latest.zip https://wordpress.org/latest.zip
    unzip -q latest.zip
    mv wordpress/* .
    rmdir wordpress
    rm -f latest.zip
    
    # 设置权限
    chown -R www-data:www-data /var/www/html/wordpress
    find /var/www/html/wordpress -type d -exec chmod 755 {} \;
    find /var/www/html/wordpress -type f -exec chmod 644 {} \;
    
    # 配置Nginx
    cat > /etc/nginx/sites-available/wordpress <<'EOF'
server {
    listen 80;
    server_name _;
    root /var/www/html/wordpress;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}
EOF

    ln -sf /etc/nginx/sites-available/wordpress /etc/nginx/sites-enabled/
    rm -f /etc/nginx/sites-enabled/default
    
    nginx -t
    systemctl reload nginx
    
    log_success "网站配置完成"
}

# 配置WordPress
configure_wordpress() {
    log_info "配置WordPress..."
    
    cd /var/www/html/wordpress
    
    # 读取密码
    MYSQL_WP_PASSWORD="WpPassword123!"
    
    # 创建配置文件
    cp wp-config-sample.php wp-config.php
    
    # 设置数据库信息
    sed -i "s/database_name_here/wordpress/" wp-config.php
    sed -i "s/username_here/wordpress_user/" wp-config.php
    sed -i "s/password_here/$MYSQL_WP_PASSWORD/" wp-config.php
    
    # 添加基本配置
    cat >> wp-config.php <<'EOF'

/** 基本配置 */
define('WP_DEBUG', false);
define('WP_MEMORY_LIMIT', '256M');

/** 安全密钥 */
EOF

    # 添加安全密钥
    curl -s https://api.wordpress.org/secret-key/1.1/salt/ >> wp-config.php
    
    log_success "WordPress配置完成"
}

# 显示信息
show_info() {
    log_success "=== 安装完成 ==="
    echo ""
    echo "网站地址: http://$(hostname -I | awk '{print $1}')/"
    echo ""
    echo "数据库信息:"
    echo "数据库名: wordpress"
    echo "用户名: wordpress_user" 
    echo "密码: WpPassword123!"
    echo "Root密码: RootPassword123!"
    echo ""
    echo "请访问网站完成WordPress安装"
}

# 主安装流程
main() {
    check_root
    
    log_info "开始安装WordPress环境..."
    
    # 重置并重新安装MySQL
    reset_mysql
    install_mysql_fresh
    configure_mysql_manual
    
    # 安装其他组件
    install_nginx
    install_php
    install_redis
    setup_website
    configure_wordpress
    
    show_info
}

# 运行主函数
main "$@"